﻿CREATE PROCEDURE [dbo].[Note_Save]
	@noteId BIGINT,
	@textId BIGINT,
	@userId	UNIQUEIDENTIFIER,
	@value NVARCHAR(MAX),
	@title NVARCHAR(256)
AS
BEGIN
	IF EXISTS (SELECT * FROM [dbo].[mark_Note] WHERE [NoteId] = @noteId AND [UserId] = @userId AND [TextId] = @textId)
	BEGIN
		UPDATE [dbo].[mark_Note]
		SET	[Value] = @value
				,	[Title] = CASE 
											WHEN [IsUserTitle] = 1 
											THEN [Title] 
											ELSE @title 
										END
		WHERE [NoteId] = @noteId AND [UserId] = @userId AND [TextId] = @textId
	END
	ELSE
	BEGIN
		INSERT INTO [dbo].[mark_Note]
							 ([TextId]
							 ,[Value]
							 ,[Title]
							 ,[UserId])
				 VALUES
							 (@textId			--<TextId, bigint,>
							 ,@value			--<Value, nvarchar(max),>
							 ,@title			--<Title, nvarchar(256),>
							 ,@userId			--<UserId, uniqueidentifier,>
							 )

		SET @noteId = SCOPE_IDENTITY()
	END

	SELECT [NoteId], [Title] FROM [dbo].[mark_Note] WHERE [NoteId] = @noteId
END